package com.finchina.myview.viewgroups;

import android.content.Context;
import android.graphics.Point;
import android.support.v4.widget.ViewDragHelper;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

/**
 * 作者：黄赛赛 on 2015/9/11 09:43
 *
 * @version V1.0
 * @Description: ${todo}()
 */
public class VDHLayout extends LinearLayout {
    private ViewDragHelper mDragger;

    private View mDragView;
    private View mAutoBackView;
    private View mEdgeTrackerView;
    private Point mAutoBackOriginPos = new Point();


    public VDHLayout(Context context) {
        this(context, null);
    }

    public VDHLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VDHLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
//        创建实例需要3个参数，第一个就是当前的ViewGroup，第二个sensitivity，主要用于设置touchSlop:
        mDragger =  ViewDragHelper.create(this,1.0f,  dragCallBack);
//        helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
//        可见传入越大，mTouchSlop的值就会越小。第三个参数就是Callback，在用户的触摸过程中会回调相关方法，后面会细说。
        mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
    }

    ViewDragHelper.Callback dragCallBack = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(View child, int pointerId) {
            //mEdgeTrackerView禁止直接移动
            return child == mDragView || child == mAutoBackView;
//            return true;
        }

        @Override
        public int clampViewPositionHorizontal(View child, int left, int dx) {

            int minleft = getPaddingLeft();
            int maxright = getWidth() - getPaddingRight() - child.getWidth();
            int newl = 0;
            if (left < minleft){
                newl = minleft;
            } else if (left > maxright) {
                newl = maxright;
            }else{
                newl =left;
            }
            return newl;
        }

        @Override
        public int clampViewPositionVertical(View child, int top, int dy) {
            int mintop = getPaddingTop();
            int maxtop = getHeight() - getPaddingBottom() - child.getHeight();
            int newtop = 0;
            if (top < mintop){
                newtop = mintop;
            }else if (top > maxtop){
                newtop = maxtop;
            }else{
                newtop = top;
            }
            return newtop;
        }

        @Override
        public void onEdgeDragStarted(int edgeFlags, int pointerId) {
//            super.onEdgeDragStarted(edgeFlags, pointerId);
            mDragger.captureChildView(mEdgeTrackerView, pointerId);

        }

        @Override
        public void onViewCaptured(View capturedChild, int activePointerId) {
            super.onViewCaptured(capturedChild, activePointerId);
//            当captureview被捕获时回调

        }

        @Override
        public void onViewDragStateChanged(int state) {
            super.onViewDragStateChanged(state);
//            当ViewDragHelper状态发生变化时回调（IDLE,DRAGGING,SETTING[自动滚动时]）
        }

        @Override
        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            super.onViewPositionChanged(changedView, left, top, dx, dy);
//            当captureview的位置发生改变时回调
        }

        @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
//            super.onViewReleased(releasedChild, xvel, yvel);
            //mAutoBackView手指释放时可以自动回去
            if (releasedChild == mAutoBackView)
            {
                mDragger.settleCapturedViewAt(mAutoBackOriginPos.x, mAutoBackOriginPos.y);
                invalidate();
            }
        }


        @Override
        public int getViewHorizontalDragRange(View child) {
            return getMeasuredWidth() - child.getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        }

        @Override
        public int getViewVerticalDragRange(View child) {
            return getMeasuredHeight() - child.getMeasuredHeight() - getPaddingBottom() - child.getPaddingTop();
        }

        @Override
        public int getOrderedChildIndex(int index) {
            return super.getOrderedChildIndex(index);
//            改变同一个坐标（x,y）去寻找captureView位置的方法。（具体在：findTopChildUnder方法中）
        }

        @Override
        public boolean onEdgeLock(int edgeFlags) {
            return super.onEdgeLock(edgeFlags);
//            true的时候会锁住当前的边界，false则unLock。

        }

        @Override
        public void onEdgeTouched(int edgeFlags, int pointerId) {
            super.onEdgeTouched(edgeFlags, pointerId);
//            当触摸到边界时回调。
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
       mDragger.processTouchEvent(event);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return mDragger.shouldInterceptTouchEvent(ev);
    }

    @Override
    public void computeScroll() {
        if (mDragger.continueSettling(true)) {
            invalidate();
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        super.onLayout(changed, l, t, r, b);

        mAutoBackOriginPos.x = mAutoBackView.getLeft();
        mAutoBackOriginPos.y = mAutoBackView.getTop();
    }

    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();

        mDragView = getChildAt(0);
        mAutoBackView = getChildAt(1);
        mEdgeTrackerView = getChildAt(2);
    }
}
